
# 预设用户信息 {用户名: {'password': 'xxx', 'current_password': 'xxx'}}
users = {
    'user1': {'password': '17514'},
    'user2': {'password': '123456'}
}

# 可借阅的图书列表
available_books = ['Python编程', '数据结构', '算法导论', '机器学习']

# 借阅记录：{用户名: [{'book': '书名', 'returned': False}, ...]}
borrow_records = {}

def login():
    print("\n欢迎使用图书管理系统")
    while True:
        username = input("请输入用户名: ").strip()
        password = input("请输入密码: ").strip()

        if username in users and users[username]['password'] == password:
            print(f"\n登录成功！欢迎, {username}！")
            return username
        else:
            print("用户名或密码错误，请重新输入。\n")

def change_password(username):
    current_pwd = input("请输入当前密码: ").strip()
    if current_pwd != users[username]['password']:
        print("当前密码错误，修改失败。")
        return

    new_pwd = input("请输入新密码: ").strip()
    confirm_pwd = input("请再次输入新密码确认: ").strip()

    if new_pwd == confirm_pwd:
        users[username]['password'] = new_pwd
        print("密码修改成功！")
    else:
        print("两次输入的新密码不一致，修改失败。")

def show_available_books():
    print("\n可借阅的图书有:")
    for i in range(len(available_books)):
        print(f"{i+1}. {available_books[i]}")
def borrow_book(username):
    show_available_books()
    book_name = input("\n请输入要借阅的图书名称: ").strip()

    if book_name not in available_books:
        print("该图书不存在于可借阅列表中。")
        return

    # 检查该用户是否已经借了这本书且未归还
    user_records = borrow_records.get(username, [])
    for record in user_records:
        if record['book'] == book_name and not record['returned']:
            print(f"您尚未归还《{book_name}》，无法重复借阅。")
            return

    # 检查是否有其他人借了这本书且未归还（简化：只看有没有未归还的记录）
    for user, records in borrow_records.items():
        for record in records:
            if record['book'] == book_name and not record['returned']:
                print(f"《{book_name}》已被其他用户借阅且未归还，暂时无法借阅。")
                return

    # 借书
    if username not in borrow_records:
        borrow_records[username] = []
    borrow_records[username].append({
        'book': book_name,
        'returned': False
    })
    print(f"借阅成功！您已借阅《{book_name}》。")

def show_user_borrowed_books(username):
    user_records = borrow_records.get(username, [])
    borrowed = [r for r in user_records if not r['returned']]
    if not borrowed:
        print("您当前没有借阅任何图书。")
        return []

    print("\n您当前借阅的图书有:")
    for idx, record in enumerate(borrowed, 1):
        print(f"{idx}. 《{record['book']}》")
    return borrowed

def return_book(username):
    borrowed_books = show_user_borrowed_books(username)
    if not borrowed_books:
        return

    book_name = input("\n请输入要归还的图书名称: ").strip()
    user_records = borrow_records.get(username, [])
    found = False

    for record in user_records:
        if record['book'] == book_name and not record['returned']:
            record['returned'] = True
            print(f"归还成功！《{book_name}》已归还。")
            found = True
            break

    if not found:
        print("该图书不在您的借阅记录中，或已经归还。")

def query_records(username):
    user_records = borrow_records.get(username, [])
    if not user_records:
        print("您还没有任何借阅记录。")
        return

    print("\n您的借阅记录:")
    for record in user_records:
        status = "已归还" if record['returned'] else "未归还"
        print(f"《{record['book']}》 - 借阅日期: {record['borrow_date']} - 状态: {status}")

def main():
    current_user = None

    while True:
        if current_user is None:
            current_user = login()
            continue

        print("\n请选择操作:")
        print("1. 修改密码")
        print("2. 借书")
        print("3. 还书")
        print("4. 查询记录")
        print("5. 退出系统")

        try:
            choice = input("请输入选项 (1-5): ").strip()
        except:
            choice = ''

        if choice == '1':
            change_password(current_user)
        elif choice == '2':
            borrow_book(current_user)
        elif choice == '3':
            return_book(current_user)
        elif choice == '4':
            query_records(current_user)
        elif choice == '5':
            confirm = input("确认退出？(y/n): ").strip().lower()
            if confirm == 'y':
                print(f"感谢使用图书管理系统，再见，{current_user}！")
                break
            else:
                pass
        else:
            print("无效选项，请输入 1~5 之间的数字。")

        # 每次操作后暂停一下，避免刷屏（可选）
        input("\n按回车键继续...")

if __name__ == "__main__":
    main()